﻿
var fs = require('fs')
var path = require('path');
const express = require('express')
const app = express()
var http = require('http').Server(app);
var bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const session = require('express-session')

var config = require('./config/config');
const CODE_CONSTANT = config.CODE_CONSTANT
var log = require("./config/log4js-config.js").getInstand;
const testRouter = require('./routes/TestRouter')

//跨域问题
app.all('/api/*', function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
	res.header("X-Powered-By",' 3.2.1');
	res.header("Content-Type", "application/json;charset=utf-8");
	next();
});

app.use(express.static(path.join(__dirname, 'public')))
// app.use(bodyParser.json()); // for parsing application/json
// app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(bodyParser())
app.use(cookieParser())
app.use(session({
	name: 'bosen_admin',
	secret: 'very secret - required', // 对session id 相关的cookie 进行签名
	saveUninitialized: true, // 是否保存未初始化的会话
	resave: true,
  cookie : {
    maxAge : 1 * 24 * 60 * 60 * 1000, // 设置 session 的有效时间，单位毫秒
  }
}))

// 不需要登陆拦截的URL
const unInterceptUrl = {
	'/api/user/login': true,
}
app.use('/api/*', function(req, res, next){
	const originalUrl = req.originalUrl
	const user = req.session.user // 从session 获取 user对象
	if (unInterceptUrl[originalUrl] || user) {
		next();  //中间件传递
	} else {
	  res.send({code: CODE_CONSTANT.NO_LOGIN, msg: '未登陆', params: {}});
    res.end();
	}
})

// test
app.use('/api/test', testRouter)

// 所有没有定义的路由都请求转发到到首页,目的是为了让前端的VUEjs架构可以刷新页面[一定要写在路由的最后,不然在其后边定义的路由也会请求转发到首页]
app.get('/*', function(req, res) {
  res.sendFile(path.resolve(path.join(__dirname, 'public') + '/index.html'))
})

app.set('port', process.env.PORT || config.PORT);

var server = http.listen(app.get('port'), function() {
  log.info('start at port:' + server.address().port);
});
